package it.javaweb.actions.utenti;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import it.javaweb.beans.*;
import it.javaweb.dao.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UtenteController extends SimpleFormController {


	private UtenteDAO utenteDao;

	public void setUtenteDao(UtenteDAO utenteDao) {
		this.utenteDao = utenteDao;
	}
	public UtenteController() {

		setCommandClass( Utente.class );
	}

	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {

		Utente utente = (Utente) command;
		System.out.println( utente.getNome() );
		ValidationUtils.rejectIfEmpty( errors, "nome", null, "Campo obbligatorio" );
		ValidationUtils.rejectIfEmpty( errors, "cognome", null, "Campo obbligatorio" );
	}

	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		Utente utente = (Utente) command;
		if ( utente.getID()==0 ) {boolean control = utenteDao.addUser(utente);}
		return new ModelAndView( "redirect:/utenti/listaUtenti.html", referenceData(request));
	}

	@SuppressWarnings("unchecked")
	protected Map referenceData(HttpServletRequest request) throws Exception {
		
		Map map = new HashMap<String, List>();
		
		map.put("Profili", utenteDao.getProfili());
		map.put("Titoli", utenteDao.getTitoli());
				
		return map;
	}
	
}
